package com.goatrock.media.thisway.domain.adapter.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.log4j.Logger;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;

public class BaseAdapterImpl {
    private Logger logger = Logger.getLogger(BaseAdapterImpl.class);
    /*
     * Unmarshalls the movie xml file and returns the java object
     */
    public Object unmarshallXMLByPath(String path, Class cls) throws FileNotFoundException{
        Object obj = null;
        try{
            IBindingFactory bfact = BindingDirectory.getFactory(cls);
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();

            obj = uctx.unmarshalDocument(new FileInputStream(path),null);

        }
        catch(JiBXException je){
            logger.error("Exception during jibx unmarshalling: "+ je.getMessage());
            return null;
        }
        return obj;
    }

    public void marshallXMLByPath(String fileLocation, Object obj, Class cls){
       try{
            IBindingFactory bfact = BindingDirectory.getFactory(cls);
            IMarshallingContext mctx = bfact.createMarshallingContext();
            mctx.setIndent(4);
            try{
                mctx.marshalDocument(obj, null, Boolean.TRUE,new FileOutputStream(fileLocation));
            }catch(FileNotFoundException e){
                logger.error("File Not Found exception during marshalling: "+e.getMessage());
            }
        }
        catch(JiBXException je){
           logger.error("Exception during jibx marshalling:"+je.getMessage());
        }
    }
}
